/**
 * @Author: colpu
 * @Date: 2025-03-29 19:38:16
 * @LastEditors: colpu ycg520520@qq.com
 * @LastEditTime: 2025-10-21 17:32:16
 * @
 * @Copyright (c) 2025 by colpu, All Rights Reserved.
 */
import Router from "@koa/router";
const router = new Router();
import { join } from "node:path";
import debugFactory from "debug";
const debug = debugFactory("core:loader/mixin/router");
import { isDirectory } from "../../utils/index.js";

/**
 * @function loadRouter 路由加载器, 按目录层次组装并加载
 */
export default async function loadRouter(ctx) {
  const app = ctx.app;
  app.router = router;
  app.Router = Router;
  const directory = join(ctx.root, "src/router");
  debug("router directory %s", directory);
  const target = Object.create(null);
  const loaderRouterFile = new ctx.FileLoader({
    directory,
    target,
    inject: app,
  });
  await loaderRouterFile.parseFiles();

  // 加载 modules 目录下的 router.js 文件
  const modulesDirectory = join(ctx.root, "src/modules");
  if (isDirectory(modulesDirectory)) {
    const loaderModulesRouter = new ctx.FileLoader({
      directory: modulesDirectory,
      target,
      inject: app,
      match: '**/router.{js,ts}',
    });
    await loaderModulesRouter.parseFiles();
  }

  // 使用routers
  app.use(router.routes());
  app.use(router.allowedMethods());
}
